<?php
/**
 * wechat php test
 */


class weixin extends a_base{

    private $token;

    public function __construct(){
        parent::__construct();
        $wx_config = $this->m_public->getRowInfo('weixinconfig');
        if(empty($wx_config)){
            return false;
        }else{
            $this->token = $wx_config['token'];
        }
    }

    public function index(){
        $echoStr = $_GET["echostr"];
        if(empty($echoStr)){
            $this->receiveMsg();
            $this->responseMsg();
        }else{
            //valid signature , option
            if($this->checkSignature()){
                echo $echoStr;
                exit;
            }else{
                echo 'invail token';
                exit;
            }
        }

    }

    public function responseMsg(){
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)){
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $event = $postObj->Event;
            $time = time();

            $textTpl = "<xml>
                        <ToUserName>%s</ToUserName>
                        <FromUserName>%s</FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType>%s</MsgType>
                        <Content>%s</Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
            switch ($event) {
                case 'subscribe':/*订阅事件*/
                    $subscribe_info = $this->m_public->getRowInfo('weixinmsgreply',array('MsgReplyWay'=>1));
                    $msgType = 'text';
                    $contentStr = $subscribe_info['TxtContent'];
                    break;

                case 'CLICK':/*自定义菜单click*/
                    $event_key = $postObj->EventKey;
                    $msgType = 'text';
                    $msg_info = $this->m_public->getRowInfo('weixinmsgreply',array('KeyValue'=>trim($event_key)));
                    $contentStr = $msg_info['TxtContent'];
                    break;

                case '':/*用户回复消息*/
                    $keyword = trim($postObj->Content);
                    $msgType = 'text';

                    $msg_info = $this->m_public->getRowInfo('weixinmsgreply',array('KeyValue'=>trim($keyword)));
                    if(!empty($msg_info)){
                        $contentStr = $msg_info['TxtContent'];
                    }else{
                        $msg_info = $this->m_public->getRowInfo('weixinmsgreply',array('KeyValue'=>'default'));
//                        $msg_info['TxtContent'] = isset($msg_info['TxtContent']) ? $msg_info['TxtContent'] : '';
                        $contentStr = $msg_info['TxtContent'];
                    }
                    break;

                default:
                    $contentStr = '';
                    $msgType = 'text';
                    break;
            }

            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;


        }
    }

    /*接收消息*/
    public function receiveMsg(){
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        if (!empty($postStr)){
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $data['FromUserName'] = trim($postObj->FromUserName);
            $data['ToUserName'] = trim($postObj->ToUserName);
            $data['MsgType'] = trim($postObj->MsgType);
            $data['CreateTime'] = date('Y-m-d H:i:s',trim($postObj->CreateTime));
            $data['MsgId'] = trim($postObj->MsgId);

            /*多客服功能部分
            $textTpl = "<xml>
							<ToUserName>%s</ToUserName>
							<FromUserName>%s</FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType>%s</MsgType>
							</xml>";
            $msgType = 'transfer_customer_service';
            $time = $postObj->CreateTime;
            $resultStr = sprintf($textTpl, $data['ToUserName'], $data['FromUserName'], $time, $data['MsgType']);
            echo $resultStr;*/

            switch ($data['MsgType']) {
                case 'text':/*文本消息*/
                    $data['TxtContent'] = trim($postObj->Content);
                    break;

                case 'image':/*图片消息*/
                    $data['PicUrl'] = trim($postObj->PicUrl);
                    $data['MediaId'] = trim($postObj->MediaId);
                    break;

                case 'voice':/*语音消息*/
                    $data['Format'] = trim($postObj->Format);
                    $data['MediaId'] = trim($postObj->MediaId);
                    break;

                case 'video':/*视频消息*/
                    $data['ThumbMediaId'] = trim($postObj->thumb_media_id);
                    $data['MediaId'] = trim($postObj->MediaId);
                    break;

                case 'location':/*地理位置消息*/
                    $data['Location_X'] = trim($postObj->Location_X);
                    $data['Location_Y'] = trim($postObj->Location_Y);
                    $data['Scale'] = trim($postObj->Scale);
                    $data['Label'] = trim($postObj->Label);
                    break;

                default:
                    $data = array();
                    break;
            }
            if(!empty($data)){
                $this->m_public->addRowInfo('weixinmsg',$data);
            }

        }
    }

    private function checkSignature(){

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = $this->token;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}

?>